import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

// 从本地存储中获取加入购物车的food，若本地无，则新建一项
const car = JSON.parse(localStorage.getItem('car') || '[]')
let addButtonRect = {}

export default new Vuex.Store({
  state: {
    car: car,
    addButtonRect: addButtonRect
  },
  mutations: {
    // foodinfo包括name/price/count
    addToCar(state, foodinfo) {
      var flag = false // 状态标志位
      state.car.some(item => {
        if (item.name === foodinfo.name) {
          item.count = foodinfo.count
          flag = true
          return true
        }
      })
      if (!flag) {
        state.car.push(foodinfo)
      }
      localStorage.setItem('car', JSON.stringify(state.car))
    },
    // 更新已选中实物的信息（如：减少已选择数量等）
    updateFoodSelected(state, foodinfo) {
      state.car.some((item, index) => {
        if(item.name === foodinfo.name) {
          item.count = foodinfo.count
        }
        if(item.count === 0) {
          state.car.splice(index, 1)
          return true;
        }
      })
      localStorage.setItem('car', JSON.stringify(state.car))
    },
    empty(state) {
      state.car = []
      localStorage.setItem('car','')
    },
    commitButtonRect(state,rect) {
      state.addButtonRect = rect
      localStorage.setItem('Rect', JSON.stringify(state.addButtonRect))
    },
    // 清空缓存
    clearButtonRect(state, clear) {
      state.addButtonRect = clear || {}
    }
  },
  getters: {
    getSelectedFoods(state) {
      return state.car
    },
    // 获取所有已选中食品的对应选择数量
    getFoodCount(state) {
      var o = {}
      state.car.forEach(item => {
        o[item.name] = item.count
      })
      return o
    },
    // 获取已选择食品的总数量,并计算出总价格
    getAllFoodsCount(state) {
      var o = {
        count: 0, // 计算总数量
        amount: 0 // 计算总价格
      }
      state.car.forEach(item => {
        o.count += item.count
        o.amount += item.count * item.price
      })
      return o
    },
    getBottonRect(state) {
      // state.addButtonRect.ballFlag = true
      return state.addButtonRect      
    }
  }
})
